<!--
 * @Author: early-autumn
 * @Date: 2020-05-11 15:27:15
 * @LastEditors: early-autumn
 * @LastEditTime: 2020-06-05 14:31:07
 -->
<template>
  <div>
    <el-form inline>
      <el-form-item label="筛选">
        <el-select
          v-model="selected"
          clearable
          placeholder="请选择"
          @change="getBillingRecord"
        >
          <el-option
            v-for="option in selectOptions"
            :key="option.value"
            :label="option.label"
            :value="option.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="实收总额">
        {{ patient.overMoney | toFixed2 }}
      </el-form-item>
      <el-form-item label="欠费总额">
        <span style="color: red">
          {{ patient.arrearage | toFixed2 }}
        </span>
      </el-form-item>
    </el-form>
    <el-table v-loading="loading" border stripe :data="billingRecordData">
      <el-table-column type="expand">
        <template slot-scope="scope">
          <el-table :data="scope.row.listMainClosingEntriesVos">
            <el-table-column
              label="单据号"
              prop="yiyaMainClosingEntries.documentNum"
              align="center"
            />
            <el-table-column
              label="交易时间"
              prop="yiyaMainClosingEntries.createTime"
              min-width="160"
              align="center"
            />
            <el-table-column label="交易类型" align="center">
              <template slot-scope="scope2">
                {{ billingTypeEnum[scope2.row.yiyaMainClosingEntries.type] }}
              </template>
            </el-table-column>
            <el-table-column label="交易状态" align="center">
              <template slot-scope="scope2">
                {{
                  billingStatusEnum[
                    scope2.row.yiyaMainClosingEntries.billStatus
                  ]
                }}
              </template>
            </el-table-column>
            <el-table-column label="医生" prop="doctor" align="center">
            </el-table-column>
            <el-table-column
              label="开单TC"
              prop="yiyaBillingMain.tc"
              align="center"
            ></el-table-column>
            <el-table-column label="实收（元）" align="center" min-width="100">
              <template slot-scope="scope2">
                {{
                  scope2.row.yiyaMainClosingEntries.type === 3
                    ? `-${scope2.row.yiyaMainClosingEntries.thisPay}`
                    : scope2.row.yiyaMainClosingEntries.thisPay
                }}
              </template>
            </el-table-column>
            <el-table-column
              label="收费方式"
              prop="payMethods"
              align="center"
            ></el-table-column>
            <el-table-column
              label="备注"
              prop="yiyaMainClosingEntries.closingRemarks"
              align="center"
              min-width="150"
            ></el-table-column>
            <el-table-column
              v-if="!marketPath"
              label="操作"
              width="280"
              align="center"
            >
              <template slot-scope="scope2">
                <el-button
                  type="primary"
                  size="mini"
                  @click="handlePrintAccounts(scope2.row)"
                >
                  打印
                </el-button>
                <el-button
                  type="warning"
                  size="mini"
                  @click="handleChangeDoctor(scope2.row)"
                >
                  变更医生
                </el-button>
                <el-button
                  type="warning"
                  size="mini"
                  @click="handleRemarks(scope2.row.yiyaMainClosingEntries)"
                >
                  修改备注
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-table-column>
      <el-table-column
        label="操作门店"
        prop="mainClosingEntriesVo.yiyaBillingMain.clinic"
        align="center"
      ></el-table-column>
      <el-table-column
        label="首次收费时间"
        prop="mainClosingEntriesVo.yiyaBillingMain.firstBilling"
        width="160"
        align="center"
      ></el-table-column>
      <el-table-column label="账单状态" align="center">
        <template slot-scope="scope">
          {{
            billStatusEnum[
              scope.row.mainClosingEntriesVo.yiyaBillingMain.status
            ]
          }}
        </template>
      </el-table-column>
      <el-table-column
        label="开单TC"
        prop="mainClosingEntriesVo.yiyaBillingMain.tc"
        align="center"
      ></el-table-column>
      <el-table-column label="应收（元）" min-width="100" align="center">
        <template slot-scope="scope">
          {{
            scope.row.mainClosingEntriesVo.yiyaBillingMain.receivable | toFixed2
          }}
        </template>
      </el-table-column>
      <el-table-column label="实收（元）" min-width="100" align="center">
        <template slot-scope="scope">
          {{
            scope.row.mainClosingEntriesVo.yiyaBillingMain.payAmount | toFixed2
          }}
        </template>
      </el-table-column>
      <el-table-column
        label="优惠抵扣（元）"
        min-width="120"
        align="center"
        prop="mainClosingEntriesVo.total.deductionAmount"
      ></el-table-column>
      <el-table-column label="欠费汇总（元）" min-width="120" align="center">
        <template slot-scope="scope">
          {{
            scope.row.mainClosingEntriesVo.yiyaBillingMain.owingAmount
              | toFixed2
          }}
        </template>
      </el-table-column>
      <el-table-column
        min-width="160"
        label="备注"
        align="center"
        prop="mainClosingEntriesVo.yiyaBillingMain.remarks"
      ></el-table-column>
      <el-table-column
        v-if="!marketPath"
        label="操作"
        width="320"
        align="center"
      >
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="mini"
            @click="handleBillingProject(scope.row.mainClosingEntriesVo)"
          >
            详情
          </el-button>
          <el-button
            type="primary"
            size="mini"
            @click="handlePrintAccounts(scope.row.mainClosingEntriesVo)"
          >
            打印
          </el-button>
          <el-button
            type="warning"
            size="mini"
            @click="handleChangeDoctor(scope.row.mainClosingEntriesVo)"
          >
            变更医生
          </el-button>
          <el-button
            v-if="
              scope.row.mainClosingEntriesVo.yiyaBillingMain.clinic ===
              clinicName
            "
            type="warning"
            size="mini"
            @click="handleRefundApplication(scope.row.mainClosingEntriesVo)"
          >
            退款
          </el-button>
        </template>
      </el-table-column>
      <empty slot="empty"></empty>
    </el-table>
    <refund-application
      v-model="refundApplication.visible"
      :data="refundApplication.data"
      @ok="getBillingRecord"
    ></refund-application>
    <billing-project
      v-model="billingProject.visible"
      :data="billingProject.data"
    ></billing-project>
    <change-doctor
      v-model="changeDoctor.visible"
      :data="changeDoctor.data"
      @ok="getBillingRecord"
    ></change-doctor>
    <print-panel
      v-model="printAccounts.visible"
      path="/print/accounts"
      :data="printAccounts.data"
      width="1000px"
    ></print-panel>
  </div>
</template>

<script>
import { billingRecord } from '@/api/services/billingMain'
import { deepCopy } from '@/utils/utils'
import {
  billStatusEnum,
  billingTypeEnum,
  billingStatusEnum,
} from '@/utils/enums'
import { billingRecordDataTransform } from '../../utils'
import { mapState } from 'vuex'
import { updateEntries } from '@/api/services/entries'

import toFixed2 from '@/filters/toFixed2'

export default {
  name: 'BillingRecord',
  components: {
    PrintPanel: () => import('@/components/yiya/PrintPanel'),
    Empty: () => import('@/components/yiya/Empty'),
    RefundApplication: () => import('./RefundApplication'),
    BillingProject: () => import('./BillingProject'),
    ChangeDoctor: () => import('./ChangeDoctor'),
  },
  filters: {
    toFixed2,
  },
  props: {
    patient: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      loading: false,
      selectOptions: [
        { label: '全部', value: '' },
        { label: '未结清', value: '1' },
        { label: '已结清', value: '2' },
        { label: '退款', value: '3' },
      ],
      selected: '',
      billingRecordData: [],
      refundApplication: {
        visible: false,
        data: {
          yiyaBillingMain: {},
          yiyaItemBillingExtends: [],
          total: {},
        },
      },
      billingProject: {
        visible: false,
        data: {
          yiyaBillingMain: {},
          yiyaItemBillingExtends: [],
          total: {},
        },
      },
      changeDoctor: {
        visible: false,
        data: {
          yiyaBillingMain: {},
          yiyaItemBillingExtends: [],
          total: {},
        },
      },
      printAccounts: {
        visible: false,
        data: {},
      },
      marketPath: false,
    }
  },
  watch: {
    patient(val) {
      this.getBillingRecord()
      this.marketStatus()
    },
    deep: true,
    immediate: true,
  },
  computed: {
    ...mapState({
      clinicName: (state) => state.clinic.clinicName,
    }),
    billStatusEnum() {
      return billStatusEnum
    },
    billingTypeEnum() {
      return billingTypeEnum
    },
    billingStatusEnum() {
      return billingStatusEnum
    },
    selectedQuery() {
      return {
        '': {},
        1: {
          mainStatus: 1,
        },
        2: {
          mainStatus: 2,
        },
        3: {
          type: 3,
        },
      }[this.selected]
    },
  },
  mounted() {
    this.getBillingRecord()
    this.marketStatus()
  },
  methods: {
    //判断是否市场查看
    marketStatus() {
      if (this.$route.path === '/userMessageHandle/userHandle') {
        this.marketPath = true
      }
    },
    async getBillingRecord() {
      try {
        this.loading = true
        const { rows } = await billingRecord({
          ...this.selectedQuery,
          billStatus: billingStatusEnum['已结账'],
          clinicPersonId: this.patient.id,
        })
        this.billingRecordData = billingRecordDataTransform(rows || [])
      } finally {
        this.loading = false
      }
    },
    handleRefundApplication(order) {
      this.refundApplication = {
        visible: true,
        data: deepCopy(order),
      }
    },
    handleBillingProject(order) {
      this.billingProject = {
        visible: true,
        data: deepCopy(order),
      }
    },
    handleChangeDoctor(order) {
      this.changeDoctor = {
        visible: true,
        data: deepCopy(order),
      }
    },
    async handleRemarks(e) {
      const { value: closingRemarks } = await this.$prompt('备注', '修改备注', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValue: e.closingRemarks,
        inputPlaceholder: '请输入备注',
        inputValidator: (e) => !!(e && e.trim()),
        inputErrorMessage: '备注不能为空',
      })
      await updateEntries({ id: e.id, closingRemarks })
      this.msgSuccess('修改成功')
      await this.getBillingRecord()
    },
    handlePrintAccounts(data) {
      this.printAccounts = { visible: true, data: data }
    },
  },
}
</script>
